package net.xujialiang.XTestRPA.Repository.Env;

import net.xujialiang.XTestRPA.Entity.Env.XRPAEnv;
import net.xujialiang.XTestRPA.Entity.RPA.XRPATask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;
import java.util.Optional;

public interface EnvRepository extends CrudRepository<XRPAEnv, Integer> {
    List<XRPAEnv> findAllByTtc(String ttc);
    Optional<XRPAEnv> findByIdAndTtc(Integer id, String ttc);
    Optional<XRPAEnv> findByEnvIDAndTtc(String envID, String ttc);

    Page<XRPAEnv> findAllByTtc(String ttc, Pageable pageable);
    Page<XRPAEnv> findAllByTtcAndGroupID(String ttc, String GroupID, Pageable pageable);
    List<XRPAEnv> findAllByGroupID(String GroupID);

    long countByTtc(String ttc);

    @Query(value = "select * from ENV where id in (SELECT DISTINCT ENV.ID FROM ENV LEFT JOIN ENVANDENVTAG on ENVANDENVTAG.ENVID = ENV.ENVID WHERE (:groupID is null or ENV.GROUPID = :groupID) and (:envName is null or ENV.ENVNAME LIKE %:envName%) and (:tagIds is null or TAGID IN (:tagIds)) and (ENV.TTC = :ttc) ) order by mOrder desc,ID desc",
            countQuery = "SELECT count(ENV.ID) FROM ENV LEFT JOIN ENVANDENVTAG on ENVANDENVTAG.ENVID = ENV.ENVID WHERE GROUPID = :groupID and TTC = :ttc and ENVNAME LIKE %:envName% and TAGID IN (:tagIds)",
            nativeQuery = true)
    Page<XRPAEnv> findByEnvNameAndGroupIdAndByTagIds(String groupID, String envName, List<String> tagIds, String ttc, Pageable pageable);

}
